//
//  WDFinancialProductController.m
//  Zhihuijinfu
//
//  Created by 王笛 on 2016/11/30.
//  Copyright © 2016年 王笛. All rights reserved.
//

#import "WDFinancialProductController.h"
#import "WDProduct.h"
#import "WDProductCell.h"
#import "WDProductDetailController.h"
#import "WDPlaceholderView.h"
#import "WDCustomMenuItem.h"
#import "WDSelectView.h"
#import "WDSelectData.h"
#import "WDPlaceholderView.h"


static NSInteger const headViewH = 44;

@interface WDFinancialProductController () < UITableViewDelegate, UITableViewDataSource, WDCustomMenuItemDelegate, WDSeleViewDelegate>
/** 车型数组 */
@property (nonatomic, strong) NSArray *carType;
/** 筛选菜单栏 */
@property (nonatomic, strong) UIView *menuView;
/** tableView */
@property(nonatomic, weak) UITableView *tableView;
/** 数据数组 */
@property (nonatomic, strong) NSMutableArray *dataArray;

/** 一页显示多少 */
@property (assign, nonatomic) NSInteger numberOfPage;
@property (assign, nonatomic) NSInteger currentPage;
@property (assign, nonatomic) NSInteger totalPage;
@property (assign, nonatomic) BOOL firstCome;
@property (assign, nonatomic) NSInteger count;
/** 适用业务数组 */
@property (nonatomic, strong) NSArray *operationArr;
/** 临时按钮 */
@property (nonatomic, strong) UIButton *tempBtn;
/** 适用业务按钮 */
@property (nonatomic, strong) UIButton *operationBtn;
/** 筛选按钮 */
@property (nonatomic, strong) UIButton *serchBtn;
@property (assign, nonatomic) BOOL isPassRate;
/** 适用业务 */
@property (assign, nonatomic) NSInteger operationNum;
/** 适用菜单 */
@property (nonatomic, strong) WDCustomMenuItem *menuItem;
/** 选中的筛选条件 */
@property (nonatomic, strong) NSArray *contentArr;
/** 占位图 */
@property (strong, nonatomic) WDPlaceholderView *placeView;

@end

@implementation WDFinancialProductController


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.firstCome = YES;
    self.isPassRate = NO;
    self.operationNum = 0;
    
    self.dataArray = [NSMutableArray array];
    
    self.view.backgroundColor = WDBackColor;
    
    //添加这句话，tableView就不会被遮盖
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    //设置导航条
    if (self.loanProduct) {
        
        [self loadNavItemWithAction:@selector(clickNavLeft) btnImage:@"icon_back" btnSelImage:@"icon_back" title:@"金融产品"];
    }else {
        [self loadNavItemWithAction:@selector(clickNavLeft) btnImage:@"actionbar" btnSelImage:@"actionbar" title:@"金融产品"];
    }
    
    [self setUpProductTaleView];
    
    [self showLoadView];
    
    //设置搜索视图
//    [self setUpMenuViewWithArr:@[@"适用业务 ", @"申请人数 ", @"通过率 ", @"筛选 "]];
//    self.operationArr = @[@"全部",@"新车",@"二手车"];
}

//设置StatusBar样式
- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self checkNewWorking];
    
    [self preferredStatusBarStyle];
    
    if (self.firstCome) {
        
        [self sendRequestData];
    }
    
}

- (void) viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
    if (self.isLoanProduct) {
        //添加边缘返回手势
        if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
            self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
        } 
        
    } else {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
        
        [self.mm_drawerController setOpenDrawerGestureModeMask:MMOpenDrawerGestureModeAll];
    }
    
    if (!self.loanProduct) {
        
        [self getNotifyCount];
    }
    
    [self.tableView reloadData];
    
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    
    [self.mm_drawerController setOpenDrawerGestureModeMask:MMOpenDrawerGestureModeNone];
}

- (void)clickNavLeft
{
    if (self.isLoanProduct) {
        
        [self.navigationController popViewControllerAnimated:YES];
        
    } else {
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@PostString object:NSStringFromClass([self class])];
        //打开抽屉效果
        [self.mm_drawerController openDrawerSide:MMDrawerSideLeft
                                        animated:YES
                                      completion:^(BOOL finished) {
                                          
                                      }];
        
    }
}

#pragma mark - <加载控件>
//加载占位图
- (void)showLoadView
{
    self.placeView = [WDPlaceholderView placeholderViewWithImageName:@"icon_loading" status:@"努力加载中..."];
    [self.view addSubview:self.placeView];
    
    [self.placeView makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(100);
        make.left.right.bottom.equalTo(0);
    }];
}

//移除占位图
- (void)hideLoadView
{
    [self.placeView removeFromSuperview];
}

- (void)setUpProductTaleView
{
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    tableView.dataSource = self;
    tableView.delegate = self;
    tableView.separatorStyle = NO;
    [self.view addSubview:tableView];
    
    self.tableView = tableView;
    
//    tableView.contentInset = UIEdgeInsetsMake(headViewH + 5, 0, 0, 0);
//    tableView.contentOffset = CGPointMake(0, - headViewH - 5);
    
    [tableView makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(0);
        make.top.equalTo(0);
    }];
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        [self sendRequestData];
        
    }];
}

- (void)setUpMenuViewWithArr:(NSArray *)menusArr
{
    UIView *menuView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WDScreenW, headViewH)];
    menuView.backgroundColor = [UIColor whiteColor];
    
    UIView *buttomLine = [[UIView alloc] initWithFrame:CGRectMake(0, headViewH - 1, WDScreenW, 1)];
    buttomLine.backgroundColor = WDBackColor;
    [menuView addSubview:buttomLine];
    
    CGFloat btnW = WDScreenW * 1.0 / menusArr.count;
    
    for (int i = 0; i < menusArr.count; i++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(btnW * i, 0, btnW, headViewH - 1);
        
        if (i == 0) {
            self.operationBtn = btn;
        }
        
        if (i == 1) {
            btn.selected = YES;
            _tempBtn = btn;
        }
        
        if (i == 3) {
            self.serchBtn = btn;
        }
        
        [btn setTitle:menusArr[i] forState:UIControlStateNormal];
        [btn setTitleColor:ColorForRGB(0x4c4c4c) forState:UIControlStateNormal];
        [btn setTitleColor:WDNavSeleColor forState:UIControlStateSelected];
        
        btn.titleLabel.font = [UIFont systemFontOfSize:15];
        if (i < menusArr.count - 1) {
            [btn setImage:[UIImage imageNamed:@"iconfont-fanhui copy 2"] forState:UIControlStateNormal];
            [btn setImage:[UIImage imageNamed:@"iconfont-hong"] forState:UIControlStateSelected];
        } else {
            [btn setImage:[UIImage imageNamed:@"iconfont-shaixuan"] forState:UIControlStateNormal];
            [btn setImage:[UIImage imageNamed:@"iconfont-shaixuan copy"] forState:UIControlStateSelected];
        }
        
        [btn setTitleEdgeInsets:UIEdgeInsetsMake(0, -btn.imageView.image.size.width, 0, btn.imageView.image.size.width)];
        [btn setImageEdgeInsets:UIEdgeInsetsMake(0, btn.titleLabel.bounds.size.width, 0, -btn.titleLabel.bounds.size.width)];
        
        btn.tag = i;
        [btn addTarget:self action:@selector(clickMenu:) forControlEvents:UIControlEventTouchUpInside];
        [btn setBackgroundImage:[UIImage imageWithColor:[UIColor colorWithWhite:0.3 alpha:0.4]] forState:UIControlStateHighlighted];
        
        [menuView addSubview:btn];
    }
    
    [self.view addSubview:menuView];
    
}

//点击按钮
- (void)clickMenu:(UIButton *)sender
{
    switch (sender.tag) {
        case 0:
        {
            //适用业务
            self.operationBtn.selected = !self.operationBtn.selected;
            
            if (self.operationBtn.selected) {//创建
                
                NSInteger seleNum;
                
                NSString *titleText = [NSString stringWithFormat:@"%@", self.operationBtn.titleLabel.text];
                if ([titleText isEqualToString:@"适用业务 "]) {
                    seleNum = 0;
                } else if ([titleText isEqualToString:@"新车"]) {
                    seleNum = 1;
                } else {
                    seleNum = 2;
                }
                
                WDCustomMenuItem *menuItem = [[WDCustomMenuItem alloc] initWithDataArr:self.carType seleIndex:seleNum];
                
                self.menuItem = menuItem;
                menuItem.delegate = self;
                
                [self.view addSubview:menuItem];
                
            } else {//移除
                [self.menuItem hide];
            }
            
            
        }
            break;
            
        case 1:
        {
            if (sender.selected != _tempBtn.selected) {
                sender.selected = !sender.selected;
                self.tempBtn.selected = NO;
                self.isPassRate = NO;
                _tempBtn = sender;
                
                //按人数排序
                self.dataArray = (NSMutableArray *)[self screenArr:self.dataArray flag:self.isPassRate];
                [self.tableView reloadData];
            }
        }
            break;
            
        case 2:
        {
            if (sender.selected != _tempBtn.selected) {
                sender.selected = !sender.selected;
                _tempBtn.selected = NO;
                _tempBtn = sender;
                
                self.isPassRate = YES;
                
                //按通过率排序
                self.dataArray = (NSMutableArray *)[self screenArr:self.dataArray flag:self.isPassRate];
                [self.tableView reloadData];
            }
        }
            break;

        case 3:
        {
            //请求筛选数据
            [self PostPayAmount];
            
        }
            break;

            
        default:
            break;
    }
}

#pragma mark - 排序筛选，返回排序后的结果 
/** flog:0 人数排序 1通过率 */
- (NSArray *)screenArr:(NSArray *)arr flag:(BOOL)flag
{
    NSSortDescriptor *firstDescriptor = [[NSSortDescriptor alloc] initWithKey:@"favorite" ascending:NO];
    
    NSSortDescriptor *secondDescriptor = [[NSSortDescriptor alloc] initWithKey:@"apply_count" ascending:NO];
    
    NSSortDescriptor *thirdDescriptor = [[NSSortDescriptor alloc] initWithKey:@"pass_rate" ascending:NO];
    
    NSArray *sortDescriptors;
    if (!flag) {
        sortDescriptors = @[firstDescriptor,secondDescriptor,thirdDescriptor];
    } else {
        sortDescriptors = @[firstDescriptor, thirdDescriptor, secondDescriptor];
    }
    
    
    
    NSArray *sortArray = [arr sortedArrayUsingDescriptors:sortDescriptors];
    
    return sortArray;
}

#pragma mark - 请求数据
- (void)sendRequestData
{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    
    manager.requestSerializer.timeoutInterval = 10.0f;
    
    NSData *cookiesdata = [[NSUserDefaults standardUserDefaults] objectForKey:WDURLLogin];
    if([cookiesdata length]) {
        NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData:cookiesdata];
        NSHTTPCookie *cookie;
        for (cookie in cookies) {
            [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
        }
    }
    
    NSString *url = [NSString stringWithFormat:@"%@%@", WDURLPrefix, WDURLProductList];
    
    NSString *time_stamp = [[NSUserDefaults standardUserDefaults] objectForKey:@"time_stampF"];
    
    time_stamp = (time_stamp == nil ? @"" : time_stamp);
    
    NSDictionary *parameters = @{
                                 @"time_stamp":time_stamp,
                                 @"city_id":[[NSUserDefaults standardUserDefaults] objectForKey:@"workCity"],
                                 @"ctype":@3
                                 };
    
    [manager POST:url parameters:parameters constructingBodyWithBlock:nil
         progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
             
             [self hideLoadView];
             
             [self.tableView.mj_header endRefreshing];
             
             NSMutableArray *models = [WDProduct mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
             
             NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
             
             [userDefault setObject:responseObject[@"time_stamp"] forKey:@"time_stampF"];
             
             //保存到数据库中
             WDSQLiteManager *manager = [WDSQLiteManager manager];
             
             [manager creatTable:NSStringFromClass([WDProduct class]) WithPrimaryKey:@[@"id"]];
             [manager insertWithTable:NSStringFromClass([WDProduct class]) andModelArr:models];
             
             //从数据库中读数据
             
             //贷款产品筛选
             if (self.isLoanProduct) {
                 
                 NSMutableArray *products = (NSMutableArray *)[manager selectWithTable:NSStringFromClass([WDProduct class])];
                 
                 WDProduct *productTemp = nil;
                 
                 NSMutableArray *loanProducts = [NSMutableArray array];
                 
                 for (productTemp in products) {
                     if ([productTemp.financeamount_start integerValue] < [self.loanAmount integerValue] && [productTemp.financeamount_end integerValue] > [self.loanAmount integerValue] && [productTemp.term containsString:self.loanTerm] && [productTemp.car_type boolValue] == self.loanCarType) {
                         
                         [loanProducts addObject:productTemp];
                         
                     }
                     
                     self.dataArray = (NSMutableArray *)[self screenArr:loanProducts flag:self.isPassRate];
                     
                     [self.tableView reloadData];
                 }
                 
                 if (_firstCome) {
                     if (!self.dataArray.count) {
                                                  WDPlaceholderView *placehView = [WDPlaceholderView placeholderViewWithImageName:@"icon_loadFailed" status:@"目前暂无产品"];
                         
                         [self.view addSubview:placehView];
                         
                         [placehView makeConstraints:^(MASConstraintMaker *make) {
                             make.top.equalTo(100);
                             make.left.right.equalTo(0);
                         }];
                     }
                 }
                 
             } else {
                 
                 WDLog(@"%@", NSHomeDirectory());
                 
                 NSArray *loanProducts = [manager selectWithTable:NSStringFromClass([WDProduct class])];
                 
                 self.dataArray = (NSMutableArray *)[self screenArr:loanProducts flag:0];
                 
                 [self.tableView reloadData];
             }
             
             self.firstCome = NO;
             
         } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
             
             [self hideLoadView];
             
             self.firstCome = NO;
             
             //从数据库中读数据
             WDSQLiteManager *manager = [WDSQLiteManager manager];
             
             NSArray *loanProducts = [manager selectWithTable:NSStringFromClass([WDProduct class])];
             
             self.dataArray = (NSMutableArray *)[self screenArr:loanProducts flag:self.isPassRate];
             
             [self.tableView reloadData];
             
             [self.tableView.mj_header endRefreshing];
             
             //WDLog(@"%@",error);
         }];
}

- (void)PostPayAmount
{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    
    manager.requestSerializer.timeoutInterval = 10.0f;
    
    NSData *cookiesdata = [[NSUserDefaults standardUserDefaults] objectForKey:WDURLLogin];
    if([cookiesdata length]) {
        NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData:cookiesdata];
        NSHTTPCookie *cookie;
        for (cookie in cookies) {
            [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
        }
    }
    
    NSString *url = [NSString stringWithFormat:@"%@%@", WDURLPrefix, WDURLListdownpaymentrate];
    
    NSDictionary *parameters = @{
                                 @"ctype":@3
                                 };
    
    [manager POST:url parameters:parameters constructingBodyWithBlock:nil
         progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
             //WDLog(@"%@", responseObject[@"data"]);
             
             NSArray *dataArray = [WDSelectData mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
             
             //筛选条件
             WDSelectView *seleView = [[WDSelectView alloc] initWithFrame:CGRectMake(0, 0, WDScreenW, WDScreenH)];
             seleView.dataArr = dataArray;
             seleView.seleStrArr = self.contentArr;
             seleView.delegate = self;
             [self.view addSubview:seleView];
             
         } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
             
             //WDLog(@"%@",error);
         }];
}

#pragma mark - 查看有没有通知
- (void)getNotifyCount
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    NSData *cookiesdata = [[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:@"%@%@", WDURLPrefix, WDURLLogin]];
    if([cookiesdata length]) {
        NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData:cookiesdata];
        NSHTTPCookie *cookie;
        for (cookie in cookies) {
            [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
        }
    }
    
    NSDictionary *parameters = @{
                                 @"ctype":@3
                                 };
    
    NSString *url = [NSString stringWithFormat:@"%@%@", WDURLPrefix, WDURLGetNotice];
    
    [manager POST:url parameters:parameters constructingBodyWithBlock:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        //WDLog(@"当前通知个数 = %@", responseObject[@"count"]);
        
        if ([responseObject[@"count"] boolValue]) {//有通知
            
            [self setNavLeftBtnWithAction:@selector(clickNavLeft) leftBtnImage:@"icon-baidian" leftBtnSelImage:@"icon-baidian"];
            
            //设置图标个数
            [UIApplication sharedApplication].applicationIconBadgeNumber = [responseObject[@"count"] integerValue];
            
            [GeTuiSdk setBadge:[responseObject[@"count"] integerValue]];
            
        } else {//没有通知
            
            [self setNavLeftBtnWithAction:@selector(clickNavLeft) leftBtnImage:@"actionbar" leftBtnSelImage:@"actionbar"];
            
            //设置图标个数
            [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
            
            [GeTuiSdk setBadge:0];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        //WDLog(@"%@", error);
        
    }];
    
}

#pragma mark - lazy load
- (NSArray *)carType
{
    if (!_carType) {
        _carType = @[@"全部", @"新车", @"二手车"];
    }
    return _carType;
}

#pragma mark - <WDCustoMenuDelegate>
- (void)customMenuItem:(WDCustomMenuItem *)sheet clickIndex:(NSUInteger)index
{
    self.operationBtn.selected = NO;
    if (index == 0) {
        [self.operationBtn setTitle:@"适用业务 " forState:UIControlStateNormal];
        
    } else {
        [self.operationBtn setTitle:self.carType[index] forState:UIControlStateNormal];
    }
    
    self.operationNum = index;
    
    WDSQLiteManager *manager = [WDSQLiteManager manager];
    
    if (self.operationNum == 0) {
        NSArray *loanProducts = [manager selectWithTable:NSStringFromClass([WDProduct class])];
        
        _dataArray = (NSMutableArray *)[self screenArr:loanProducts flag:self.isPassRate];
    } else if (self.operationNum == 1) {
        
        NSArray *loanProducts = [manager selectWithTable:NSStringFromClass([WDProduct class]) whereCondition:@{@"car_type":@0}];
        
        _dataArray = (NSMutableArray *)[self screenArr:loanProducts flag:self.isPassRate];
        
    } else {
        
        NSArray *loanProducts = [manager selectWithTable:NSStringFromClass([WDProduct class]) whereCondition:@{@"car_type":@1}];
        
        _dataArray = (NSMutableArray *)[self screenArr:loanProducts flag:self.isPassRate];
        
    }

    
    [self.tableView reloadData];
    
    [self.operationBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, -self.operationBtn.imageView.image.size.width, 0, self.operationBtn.imageView.image.size.width)];
    [self.operationBtn setImageEdgeInsets:UIEdgeInsetsMake(0, self.operationBtn.titleLabel.bounds.size.width, 0, -self.operationBtn.titleLabel.bounds.size.width)];
}

- (void)touchMove
{
    self.operationBtn.selected = NO;
}

#pragma mark - <WDSelectViewDelegate>
- (void)selectArrData:(NSArray *)arrData
{
    self.contentArr = arrData;
    
    if (arrData.count) {
        self.serchBtn.selected = YES;
    } else {
        self.serchBtn.selected = NO;
    }
    
    //筛选数据
    
    
}

#pragma mark - <UITableViewDataSource>
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 9.0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WDProductCell *cell = [WDProductCell productCellWithTableView:tableView];
    
    cell.product = self.dataArray[indexPath.section];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (self.isLoanProduct) {
        WDProduct *tempProduct = self.dataArray[indexPath.section];
        //返回上一页，把名字和productID传回去
        if (self.productData) {
            self.productData(tempProduct);
        }
        
        [self.navigationController popViewControllerAnimated:YES];
    } else {
        
        WDProduct *product = self.dataArray[indexPath.section];
        //跳转金融产品详情页
        WDProductDetailController *tempV = [[WDProductDetailController alloc] init];
        
        tempV.product = product;
        
        tempV.productID = ^(NSString *pid, BOOL isChange){
           
            if (isChange) {
                WDProduct *product = nil;
                int i = 0;
                
                //从数据库中读数据
                WDSQLiteManager *manager = [WDSQLiteManager manager];
                
                NSArray *loanProducts = [manager selectWithTable:NSStringFromClass([WDProduct class])];
                
                NSSortDescriptor *firstDescriptor = [[NSSortDescriptor alloc] initWithKey:@"favorite" ascending:NO];
                
                NSSortDescriptor *secondDescriptor = [[NSSortDescriptor alloc] initWithKey:@"apply_count" ascending:NO];
                
                NSArray *sortDescriptors = @[firstDescriptor, secondDescriptor];
                
                NSArray *sortArray = [loanProducts sortedArrayUsingDescriptors:sortDescriptors];
                
                self.dataArray = (NSMutableArray *)sortArray;
                
                for (product in self.dataArray) {
                    if([product.id isEqualToString:pid]) {
                        break;
                    }
                    i++;
                }
                NSIndexPath *scrollIndexPath = [NSIndexPath indexPathForRow:0 inSection:i];
                [self.tableView scrollToRowAtIndexPath:scrollIndexPath atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
            }
            
        };
        
        tempV.view.backgroundColor = WDBackColor;
        [self.navigationController pushViewController:tempV animated:YES];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WDProduct *product = self.dataArray[indexPath.section];
    return product.sessionH;
}

- (void)checkNewWorking
{
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
                
                [WDPromptBox showPromptBoxWithMassage:@"未识别的网络"];
                
                break;
                
            case AFNetworkReachabilityStatusNotReachable:
                [WDPromptBox showPromptBoxWithMassage:@"网络连接中断"];
                break;
                
            case AFNetworkReachabilityStatusReachableViaWWAN:
                
                break;
                
            case AFNetworkReachabilityStatusReachableViaWiFi:
                
                break;
            default:
                break;
        }
        
    }];
    
    //开始监听
    [manager startMonitoring];
    
}

@end
